package cn.yuhao.goodbook.user.service;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.management.RuntimeErrorException;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
import cn.yuhao.goodbook.user.dao.UserDao;
import cn.yuhao.goodbook.user.domain.User;


public class UserService {
	private UserDao userDao=new UserDao();
	public boolean ajaxValidateLoginname(String loginname){
		return userDao.ajaxValidateLoginname(loginname);
	}
	public boolean ajaxValidateEmail(String email){
		return userDao.ajaxValidateEmail(email);
	}
	public void regist(User user){
		user.setUuid(CommonUtils.uuid());
		user.setStatus(0);
		user.setActivationCode(CommonUtils.uuid()+CommonUtils.uuid());
		userDao.add(user);
		Properties prop=new Properties();
		try {
			prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
		} catch (IOException e) {
			throw new RuntimeException();
		}
		String username=prop.getProperty("username");
		String password=prop.getProperty("password");
		String host=prop.getProperty("host");
		String from=prop.getProperty("from");
		String subject=prop.getProperty("subject");
		String content=MessageFormat.format(prop.getProperty("content"), user.getActivationCode());
		String to=user.getEmail();
		
		Session session=MailUtils.createSession(host, username, password);
		Mail mail=new Mail(from, to, subject, content);
		try {
			MailUtils.send(session, mail);
		} catch (MessagingException e) {
			throw new RuntimeException();
		} catch (IOException e) {
			throw new RuntimeException();
		}
	}
}
